package com.xindong.paking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xindong.paking.dtos.MonthMoneyDto;
import com.xindong.paking.dtos.MonthOrderDto;
import com.xindong.paking.dtos.OrderDTO;
import com.xindong.paking.entity.ParkingLot;
import com.xindong.paking.entity.TbOrder;
import com.xindong.paking.entity.TbSpace;
import com.xindong.paking.entity.TbUser;
import com.xindong.paking.entity.constant.Constants;
import com.xindong.paking.mapper.*;
import com.xindong.paking.service.TbBalanceService;
import com.xindong.paking.service.TbOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindong.paking.service.TbSpaceService;
import com.xindong.paking.utils.ChangeUtil;
import com.xindong.paking.utils.Result;
import com.xindong.paking.utils.UserInfoUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jielun
 * @since 2023-01-08
 */
@Service
@SuppressWarnings("all")
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder> implements TbOrderService {

    @Autowired
    private TbBalanceService tbBalanceService;

    @Autowired
    private ParkingLotMapper parkingLotMapper;

    @Autowired
    private TbOrderMapper mapper;

    @Autowired
    private TbUserMapper userMapper;

    @Autowired
    private TbSpaceService tbSpaceService;

    @Autowired
    private ChangeUtil changeUtil;

    @Override
    public Result queryByUser(int userId, Integer status) {
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
        if (status != null) {
            wrapper.eq("status",status);
        }
        wrapper.eq("user_id",userId);
        List<TbOrder> list = mapper.selectList(wrapper);
        return Result.success("查询成功",list);
    }

    @Override
    public Result queryBycondition(String userName, String carNumber, Integer status, Date startTime, Date endTime,Integer page,Integer pageSize) {
        Page<TbOrder> pageParam = new Page<>(page, pageSize);
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("end_time");
        if (userName != null) {
            // 根据用户名模糊查询出用户ID
            QueryWrapper<TbUser> wrapper1 = new QueryWrapper<>();
            wrapper1.like("username",userName);
            List<TbUser> userIds = userMapper.selectList(wrapper1);
            ArrayList<Integer> list = new ArrayList<>();
            for (TbUser userId : userIds) {
                list.add(userId.getId());
            }
            wrapper.in("user_id",list);
        }
        if (carNumber != null && !"".equals(carNumber)) {
            wrapper.like("car_number",carNumber);
        }
        if (status != null) {
            wrapper.eq("status",status);
        }
        if (startTime != null) {
            wrapper.ge("start_time",startTime);
        }
        if (endTime != null){
            wrapper.le("end_time",endTime);
        }
        Page<TbOrder> list = mapper.selectPage(pageParam, wrapper);
        Page<OrderDTO> orderDTOPage = changeUtil.changePageModel(list,page,pageSize);
        return Result.success("查询成功",orderDTOPage);
    }

    @Override
    public Result finishOrder(Integer orderId) {
        // 获取订单
        TbOrder tbOrder = mapper.selectById(orderId);
        // 设置结束时间、订单状态、订单金额
        LocalDateTime endTime = LocalDateTime.now();
        tbOrder.setEndTime(endTime);
        tbOrder.setStatus(2);
        LocalDateTime startTime = tbOrder.getStartTime();
        Duration duration = Duration.between(startTime,endTime);
        long hours = duration.toHours();
        // 获取停车场单价
        ParkingLot parkingLot = parkingLotMapper.selectById(tbOrder.getParkingId());
        System.out.println("小时：" + hours);
        System.out.println("单价：" + parkingLot.getUnitPrice());
        System.out.println(parkingLot.toString());
        tbOrder.setMoney((float)(5 * hours));
//        tbOrder.setMoney((float)(parkingLot.getUnitPrice() * hours));
        int i = mapper.updateById(tbOrder);
        if (i == 1) {
            // 调用停车位service完成出库操作
            TbSpace tbSpace = new TbSpace();
            tbSpace.setId(orderId);
//            tbSpaceService.issue(tbSpace);
            return Result.success("结束订单成功", tbOrder);
        }
        return Result.error("无法正常结束订单，请重试");
    }

    @Override
    public Result getOrderMoney() {
        ArrayList<MonthMoneyDto> monthMoneyDtos = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            MonthMoneyDto monthMoneyDto = new MonthMoneyDto();
            monthMoneyDto.initData(i,mapper.getOrderMoney(i));
            monthMoneyDtos.add(monthMoneyDto);
        }
        return Result.success("获取数据成功",monthMoneyDtos);
    }

    @Override
    public Result totalOrder() {
        ArrayList<MonthOrderDto> monthOrderDtos = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            MonthOrderDto monthOrderDto = new MonthOrderDto();
            monthOrderDto.initData(i,mapper.getTotalOrder(i));
            monthOrderDtos.add(monthOrderDto);
        }
        return Result.success("获取数据成功", monthOrderDtos);
    }

    @Override
    public Result getOrderById(Integer orderid) {
        return Result.success(Constants.DEFAULT_QUERY_SUCCESS_MSG,mapper.selectById(orderid));
    }

    @Override
    public Result payForOrder(Integer orderid) {
        TbOrder tbOrder = mapper.selectById(orderid);
        Result deduction = tbBalanceService.deduction(tbOrder.getMoney().doubleValue());
        int status = deduction.getStatus();
        // 付款成功，修改订单状态
        if (status == 200){
            // 获取用户id
            Map<String, Object> userInfo = UserInfoUtil.getUserInfo();
            Integer id = (Integer)userInfo.get("id");
            tbOrder.setUserId(id);
            tbOrder.setStatus(3);
            mapper.updateById(tbOrder);
            return Result.success(Constants.DEFAULT_UPDATE_SUCCESS_MSG,tbOrder);
        }
        return Result.error(Constants.DEFAULT_UPDATE_FAIL_MSG);
    }

    @Override
    public TbOrder addOrder(Integer userId, String carNumber, Integer parkingId, Integer positionId) {
        TbOrder tbOrder = new TbOrder();
        tbOrder.setStartTime(LocalDateTime.now());
        tbOrder.setCarNumber(carNumber);
        tbOrder.setStatus(1);
        tbOrder.setUserId(userId);
        tbOrder.setParkingId(parkingId);
        tbOrder.setPositionId(positionId);
        mapper.insert(tbOrder);
        return tbOrder;
    }
}
